/***
 * Copyright (c) 2021-2031 murenchao
 * fig is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.software.fig.networking

import java.net.InetAddress
import java.net.SocketTimeoutException
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.util.Date
import org.apache.commons.net.ntp.NTPUDPClient
import org.apache.commons.net.ntp.NtpV3Packet
import org.slf4j.LoggerFactory

class DateNTPUtils {
	val static logger = LoggerFactory.getLogger(DateNTPUtils)

	def static LocalDateTime getLocalDateTime(String ip,Integer port) {
		return getLocalDateTime(ip,port,"+8" )
	}

	def static LocalDateTime getLocalDateTime(String ip,Integer port,String offset) {
		var date = new Date(DateNTPUtils.currentTimeMillis(ip,port))
		return date.toInstant().atOffset(ZoneOffset.of(offset)).toLocalDateTime()
	}

	def static long currentTimeMillis(String ip, Integer port) {
		try {
			if (ip !== null) {
				return ntpCurrentTimeMillis(ip,port);
			}
			return System.currentTimeMillis()
		} catch (Exception e) {
			logger.error("DateNTPUtils", e)
			return System.currentTimeMillis()
		}
	}

	def private static long ntpCurrentTimeMillis(String ip, Integer port) throws Exception{
		logger.info("get ntp current time millis")
		val nuc = new NTPUDPClient()
		nuc.setDefaultTimeout(50)
		var timestamp = System.currentTimeMillis();
		try {
			logger.info(ip)
			var ia = InetAddress.getByName(ip)
			var timeInfo = nuc.getTime(ia, port === null ? NtpV3Packet.NTP_PORT : port)
			timestamp = timeInfo.getMessage().getOriginateTimeStamp().getTime()
		} catch (SocketTimeoutException e) {
			logger.error("TimeoutException ", e)
		}
		if (timestamp == 0L) {
			return System.currentTimeMillis()
		}
		return timestamp
	}

}
